package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理订单定时任务
 *
 * @author normal
 * @date 2025年03月04日 下午4:49
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class OrderTask {

    private final OrderMapper orderMapper;

    /**
     * 订单超时自动取消订单
     * cron = 每分钟进行执行任务
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void processTimeoutOrders() {
        log.info("定时处理超时订单: {}", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));

        // select * from order where status = 1 and order_time < (当前时间 - 15分钟);
        LocalDateTime outOrdersTime = LocalDateTime.now().plusMinutes(-15);

        // 1. 查询待付款并且时间超过15分钟的订单
        List<Orders> lists = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, outOrdersTime);
        if (CollectionUtils.isNotEmpty(lists)) {
            // 2. 统一修改订单状态为取消、取消原因、取消时间
            lists.forEach(orders -> {
                LocalDateTime now = LocalDateTime.now();
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(now);
                orders.setCancelReason("订单超时,自动取消");
                orderMapper.update(orders);
            });

        }
    }

    /**
     * 订单状态 派送中转完成
     * cron = 每天的凌晨1点  订单统一进行完成
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder () {
        log.info("定时处理处于派送中的订单: {}", LocalDateTime.now());
        // 1. 当前前一个小时的订单
        LocalDateTime outOrdersTime = LocalDateTime.now().minusHours(1);
        List<Orders> lists = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, outOrdersTime);

        if (CollectionUtils.isNotEmpty(lists)) {
            // 2. 统一修改订单状态为取消、取消原因、取消时间
            lists.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            });
        }



    }
}
